import {observable, computed, action, runInAction, asMap} from "mobx";
import {BrowserHrm, ListViewPage} from 'weaver-mobile-page';
import {Toast} from 'weaver-mobile';
import {isEmpty, isArray, cloneDeep} from 'lodash';
import * as mobx from "mobx";
import OdocComsStore from "./OdocComsStore";

import * as API from "../../apis/odocRequest/index";

export default class OdocRequestStore {

    /**
     * 存储每个节点人力资源字段的store
     */
    nodeHrmStoreMap = {};

    /**
     *  已设定的流转
     */
    @observable
    nodeOperatorMap = {};

    /**
     *  选中的流程
     */
    workflowid = "";

    /**
     * 流程名称
     */
    workflowName = "";

    /**
     * 结束本人处理
     */
    @observable
    isend = "1";

    /**
     * 签字意见
     */
    @observable
    remark = "";

    /**
     * 名称
     */
    directname = "";

    btnforbiden = false;

    /**
     * 选择常用去向的store
     */
    @observable
    selectListStore = new ListViewPage.Store();

    /**
     * 流转去向设置列表的store
     */
    @observable
    directionListStore = new ListViewPage.Store();

    /**
     * popover是否显示
     */
    @observable
    popoverVisiable = false;

    /**
     * 保存常用去向的窗口是否显示
     */
    @observable
    modalVisible = observable.map ? observable.map({}) : asMap({});    //弹窗显示属性

    /**
     * 根路由
     * @type {string}
     */
    rootRouter = "";

    constructor() {
        this.setMember = this.setMember.bind(this);
        this.loadData = this.loadData.bind(this);
        this.saveDirection = this.saveDirection.bind(this);
        this.getTableList = this.getTableList.bind(this);
        this.resetStore = this.resetStore.bind(this);
        this.resetListStore = this.resetListStore.bind(this);
    }

    @action
    setMember(obj = {}) {
        Object.assign(this, {...obj});
    }

    @action
    setModalVisible(key, val = false) {
        this.modalVisible.set(key, val);
    }

    @action("加载数据")
    loadData(params, callback) {
        const {dialogType, isImport} = params;

        API.loadData(params).then(data => {
            const {success = 0} = data;

            if (success == 1) {
                callback && typeof callback == "function" && callback(data);

                const {nextNodeList, workflowid, workflowName} = data;
                runInAction(() => {
                    nextNodeList.forEach(item => {
                        const {nodeid} = item;
                        this.nodeHrmStoreMap[nodeid] = new BrowserHrm.Store({
                            route: this.rootRouter,
                            id: `odoc_select_hrm_${nodeid}`
                        });
                    });


                    this.directionListStore.setState({
                        data: nextNodeList,
                        loading: false,
                        refreshLoading: false,
                        isTable: false,
                        haveCheck: true
                    });
                    this.directionListStore.updateDataSource();

                    this.workflowid = workflowid + "";
                    this.workflowName = workflowName;
                });
            } else {
                const {msg} = data;
                if (!!msg) {
                    Toast.fail(msg, 2);
                }
            }
        })
    }

    @action("从常用去向导入")
    importData(params, callback) {
        API.importData(params).then(data => {
            const {success = 0} = data;
            if (success == 1) {
                callback && typeof callback == "function" && callback(data);

                const {nodeOperatorMap} = data;
                this.nodeOperatorMap = nodeOperatorMap;

                //处理节点选中的情况
                const selectedKeys = [];
                for (let key in nodeOperatorMap) {
                    //需要将key转为数字
                    selectedKeys.push(key * 1);
                }
                this.updateSelectKeys(selectedKeys);
            } else {
                const {msg} = data;
                if (!!msg) {
                    Toast.fail(msg);
                }
            }
        })
    }

    filterParam(list) {
        //删除这些不需要往服务端发送的数据
        list.map(item => {
            delete item.userList;
            delete item.sqlwhere;
            delete item.sqlwhere1;
            delete item.multiHrmStore;
        });
    }

    /**
     * 保存常用方向
     * @param param
     * @param calllback
     */
    saveDirection(para, calllback) {
        const nextDirections = this.getNextDirections();

        //删除这些不需要往服务端发送的数据
        this.filterParam(nextDirections);

        const params = {
            directname: this.directname,
            workflowid: this.workflowid,
            nextDirections: JSON.stringify(nextDirections),
            ...para,
        };

        API.saveData(params).then(data => {
            this.directname = "";
            calllback && calllback(data);
        })
    }

    getNextDirections() {
        const {data, selectedRowKeys} = this.directionListStore;
        const nextNodeList = mobx.toJS(data);
        const nodeOperatorMap = mobx.toJS(this.nodeOperatorMap);
        const selectedIdSet = new Set(mobx.toJS(selectedRowKeys));

        const operatorList = [];
        if (nextNodeList && nextNodeList.length > 0) {
            nextNodeList.forEach(item => {
                const {nodeid} = item;
                const map = nodeOperatorMap[nodeid] || {};

                let userInfo = {};
                if (!isEmpty(map)) {
                    const {userList = [], userIds, userNames} = map;
                    userInfo = {userList, userIds, userNames};
                }

                //选中
                if (selectedIdSet.has(nodeid)) {
                    operatorList.push({...item, ...userInfo});
                }
            });
        }

        return operatorList;
    }

    /**
     * 流程流转
     * @param param
     * @param callback
     */
    flowNext(param, callback) {
        const nextDirections = this.getNextDirections();

        //删除这些不需要往服务端发送的数据
        this.filterParam(nextDirections);

        const params0 = {
            ...param,
            isend: this.isend,
            nextDirections: JSON.stringify(nextDirections)
        };

        API.flowNext(params0).then(data => {
            callback && callback(data);
        })
    }

    @action("更新列表行数据")
    updateRow(recordId, rowData) {
        const nodeOperatorMap = mobx.toJS(this.nodeOperatorMap);
        const operatorMap = nodeOperatorMap[recordId];
        const {userList = []} = rowData;

        //先做删除操作
        if (operatorMap && typeof operatorMap == "object") {
            delete nodeOperatorMap[recordId];
        }

        if (userList.length > 0) {
            const newMap = cloneDeep(rowData);
            nodeOperatorMap[recordId] = newMap;
        }

        this.nodeOperatorMap = nodeOperatorMap;

        //设置表格的选中
        const selected = userList.length > 0;
        selected && this.updateSelectKeys(recordId, selected);
    }

    @action("清空已选择的人员")
    clearRow(recordId) {
        const nodeOperatorMap = mobx.toJS(this.nodeOperatorMap);
        const operatorMap = nodeOperatorMap[recordId];

        if (operatorMap && typeof operatorMap == "object") {
            delete nodeOperatorMap[recordId];
        }
        this.nodeOperatorMap = nodeOperatorMap;
        this.directionListStore.updateDataSource();
    }

    /**
     *
     * @param recordId，可以是string或者array
     * @param selected
     */
    @action("设置流转环节列表的选中")
    updateSelectKeys(recordId, selected) {
        if (isArray(recordId)) {
            //批量时，设置选中节点，所有选中的都以传入的为准，不在此范围的，取消选中
            this.directionListStore.select(recordId);
        } else {       //单个更新
            const {selectedRowKeys} = this.directionListStore;
            const idSet = new Set(mobx.toJS(selectedRowKeys));
            if (idSet.has(recordId) && !selected) {     //取消选中
                idSet.delete(recordId);
            }

            if (!idSet.has(recordId) && selected) {       //选中
                idSet.add(recordId);
            }

            this.directionListStore.select([...idSet]);
        }
    }

    @action
    getTableList(params) {
        API.getTableList(params).then(data => {
                const dataKey = data.datas;
                const current = 1;
                this.selectListStore.getData({dataKey, current});
            }
        );
    }

    @action
    resetStore() {
        this.nodeHrmStoreMap = {};
        this.nodeOperatorMap = {};
        this.workflowid = "";
        this.workflowName = "";
        this.isend = "1";
        this.remark = "";
        this.directname = "";
        this.btnforbiden = false;
        this.directionListStore = new ListViewPage.Store();
        this.popoverVisiable = false;
        this.modalVisible = observable.map ? observable.map({}) : asMap({});
    }

    @action
    resetListStore() {
        this.selectListStore = new ListViewPage.Store();
    }
}